package com.wanrui.shiro.config;

import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    // realm对象
    @Autowired
    private UserRealm userRealm;
    /**
     * shiro 3大对象
     * 1、shiroFilterFactoryBean（用户）
     * 2、DefaultWebSecurityManager（管理所有用户）
     * 3、realm对象  需要自定义类（获取数据库用户信息）
     */
     // shiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaultSecurityManager") DefaultSecurityManager defaultSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultSecurityManager);

        // 配置拦截

        /**
         * anon  无需权限
         * authc 必须认证才能登录
         * user 必须拥有  记住我  功能才能访问
         * perms 必须拥有对某个资源的权限才能访问
         * role 拥有某个角色权限才能访问
         *
         */

        Map<String, String> filterChainDefinitionMap = new HashMap<>();
        filterChainDefinitionMap.put("/add", "authc");
        filterChainDefinitionMap.put("/add", "perms[user:add]");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        // 设置登录页面，没有权限就去登录页面
        shiroFilterFactoryBean.setLoginUrl("/toLogin");

        // 配置未授权
        shiroFilterFactoryBean.setUnauthorizedUrl("/unAuthor");
        return shiroFilterFactoryBean;
    }


    // DefaultSecurityManager
    @Bean(name = "getDefaultSecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(userRealm);
        return manager;
    }
}
